<script lang="ts" setup>
import type { FileUploadItem } from '../FileUploader/types';

import { computed } from 'vue';

import { CheckOne, Copy, FileText, Share, Upload } from '@icon-park/vue-next';
import { Modal } from 'ant-design-vue';

import Button from '#/components/fluentui/Button.vue';
import { copyShareCode } from '#/utils/copy';
import { getFileIcon } from '#/utils/icon';

interface Props {
  isOpen?: boolean;
  uploadItems: FileUploadItem[];
  shareCode?: string;
  averageSpeed?: number;
  totalSize?: number;
}

interface Emits {
  (e: 'update:isOpen', value: boolean): void;
  (e: 'close'): void;
  (e: 'viewDetails'): void;
}

const props = withDefaults(defineProps<Props>(), {
  isOpen: false,
  shareCode: '',
  averageSpeed: 0,
  totalSize: 0,
});

const emit = defineEmits<Emits>();

// 计算成功上传的文件
const successItems = computed(() =>
  props.uploadItems.filter((item) => item.status === 'success'),
);

// 计算失败上传的文件
const failedItems = computed(() =>
  props.uploadItems.filter((item) => item.status === 'error'),
);

// 格式化文件大小
const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 Bytes';

  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));

  return `${Number.parseFloat((bytes / k ** i).toFixed(2))} ${sizes[i]}`;
};

// 格式化上传速度
const formatSpeed = (bytesPerSecond: number): string => {
  return `${formatFileSize(bytesPerSecond)}/s`;
};

// 复制分享码
const handleCopyShareCode = () => {
  if (props.shareCode) {
    copyShareCode(props.shareCode);
  }
};

// 关闭对话框
const handleClose = () => {
  emit('update:isOpen', false);
  emit('close');
};

// 查看详情
const handleViewDetails = () => {
  emit('viewDetails');
  handleClose();
};
</script>

<template>
  <Modal
    :open="isOpen"
    title="上传完成"
    :width="600"
    :footer="null"
    @cancel="handleClose"
    class="upload-complete-dialog"
  >
    <div class="space-y-6">
      <!-- 上传结果概览 -->
      <div class="text-center">
        <div class="mb-4 flex justify-center">
          <div
            class="flex h-16 w-16 items-center justify-center rounded-full bg-green-100"
          >
            <CheckOne theme="outline" size="32" fill="#10B981" />
          </div>
        </div>

        <h3 class="mb-2 text-xl font-semibold text-gray-900 dark:text-gray-100">
          文件上传完成！
        </h3>

        <div class="space-y-1 text-gray-600 dark:text-gray-300">
          <p>
            成功上传
            <span class="font-medium text-green-600">{{
              successItems.length
            }}</span>
            个文件
            <span v-if="failedItems.length > 0" class="text-red-600">
              ，失败 {{ failedItems.length }} 个文件
            </span>
          </p>

          <div class="flex items-center justify-center gap-4 text-sm">
            <span v-if="totalSize" class="flex items-center gap-1">
              <FileText theme="outline" size="14" />
              总大小：{{ formatFileSize(totalSize) }}
            </span>
            <span v-if="averageSpeed" class="flex items-center gap-1">
              <Upload theme="outline" size="14" />
              平均速度：{{ formatSpeed(averageSpeed) }}
            </span>
          </div>
        </div>
      </div>

      <!-- 分享码显示 -->
      <div v-if="shareCode" class="rounded-lg bg-gray-50 p-4 dark:bg-gray-800">
        <div class="mb-3 flex items-center gap-2">
          <Share
            theme="outline"
            size="18"
            fill="currentColor"
            class="text-blue-600"
          />
          <h4 class="font-medium text-gray-900 dark:text-gray-100">分享码</h4>
        </div>

        <div class="flex items-center gap-3">
          <div class="flex-1">
            <div
              class="rounded border border-green-200 bg-green-50 px-3 py-2 font-mono text-lg text-green-700 dark:border-green-700 dark:bg-green-900/30 dark:text-green-300"
            >
              {{ shareCode }}
            </div>
          </div>
          <Button appearance="primary" @click="handleCopyShareCode">
            <template #start>
              <Copy theme="outline" size="16" />
            </template>
            复制
          </Button>
        </div>
      </div>

      <!-- 文件列表 -->
      <div>
        <h4 class="mb-3 font-medium text-gray-900 dark:text-gray-100">
          上传文件列表
        </h4>

        <div class="max-h-60 space-y-2 overflow-y-auto">
          <div
            v-for="item in uploadItems"
            :key="item.id"
            class="flex items-center gap-3 rounded-lg border p-3"
            :class="{
              'border-green-200 bg-green-50 dark:border-green-700 dark:bg-green-900/20':
                item.status === 'success',
              'border-red-200 bg-red-50 dark:border-red-700 dark:bg-red-900/20':
                item.status === 'error',
              'border-gray-200 bg-gray-50 dark:border-gray-700 dark:bg-gray-800':
                item.status !== 'success' && item.status !== 'error',
            }"
          >
            <!-- 文件图标 -->
            <component
              :is="getFileIcon(item.name)"
              theme="outline"
              size="24"
              fill="currentColor"
              class="flex-shrink-0 text-gray-500"
            />

            <!-- 文件信息 -->
            <div class="min-w-0 flex-1">
              <p class="truncate font-medium text-gray-900 dark:text-gray-100">
                {{ item.name }}
              </p>
              <p class="text-sm text-gray-500 dark:text-gray-400">
                {{ formatFileSize(item.size) }}
              </p>
            </div>

            <!-- 状态图标 -->
            <div class="flex-shrink-0">
              <CheckOne
                v-if="item.status === 'success'"
                theme="outline"
                size="20"
                fill="#10B981"
              />
              <div
                v-else-if="item.status === 'error'"
                class="flex h-5 w-5 items-center justify-center rounded-full bg-red-500"
              >
                <span class="text-xs font-bold text-white">!</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="flex justify-end gap-3 pt-4">
        <Button appearance="subtle" @click="handleClose"> 关闭 </Button>

        <Button appearance="primary" @click="handleViewDetails">
          查看详情
        </Button>
      </div>
    </div>
  </Modal>
</template>

<style scoped>
.upload-complete-dialog :deep(.ant-modal-header) {
  border-bottom: 1px solid var(--border-color);
}

.upload-complete-dialog :deep(.ant-modal-content) {
  border-radius: 12px;
}

/* 滚动条样式 */
.max-h-60::-webkit-scrollbar {
  width: 6px;
}

.max-h-60::-webkit-scrollbar-track {
  background: #f1f5f9;
  border-radius: 3px;
}

.max-h-60::-webkit-scrollbar-thumb {
  background: #cbd5e1;
  border-radius: 3px;
}

.max-h-60::-webkit-scrollbar-thumb:hover {
  background: #94a3b8;
}

/* 暗色主题下的滚动条 */
.dark .max-h-60::-webkit-scrollbar-track {
  background: #374151;
}

.dark .max-h-60::-webkit-scrollbar-thumb {
  background: #6b7280;
}

.dark .max-h-60::-webkit-scrollbar-thumb:hover {
  background: #9ca3af;
}
</style>
